package com.pay.paytoken.activity;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pay.paytoken.R;
import com.pay.paytoken.activity.lock.LockManager;
import com.pay.paytoken.base.BaseTitleActivity;

import java.util.List;

import apiUtils.apis.RetrievePasswordAPI;
import apiUtils.models.AccountStateModel;
import apiUtils.models.VerifyPasswordModel;
import appUtils.AppUtil;
import appUtils.CustomAlertDoubleBtnDialog;
import appUtils.HiddenRule;
import appUtils.LogUtil;
import appUtils.SharedPreferencesManager;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static appUtils.SharedPreferencesManager.BINDING_LIST;
import static constant.ApiConstants.TASK_SUCCESS;


public class PasswordVerificationActivity extends BaseTitleActivity {
    @Bind(R.id.tv_account)
    TextView mTvAccount;
    @Bind(R.id.ed_password)
    EditText mEdPassword;
    @Bind(R.id.iv_password_show)
    ImageView mIvPasswordShow;
    @Bind(R.id.btn_commit)
    Button mBtnCommit;
    @Bind(R.id.tv_company)
    TextView mTvCompany;
    @Bind(R.id.layout_title_textName)
    TextView mLayoutTitleTextName;
    @Bind(R.id.layout_title_iv_left)
    ImageButton mLayoutTitleIvLeft;

    private HiddenRule mHiddenRule;
    private String mName;
    private String mAccount;
    private long mFirstTime = 0;
    private CustomAlertDoubleBtnDialog mDialog;
    private SharedPreferencesManager mSharedPreferencesManager;
    private Gson mGson;

    @Override
    public int setView() {
        return R.layout.activity_password_verification;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        mHiddenRule = new HiddenRule();
        mDialog = new CustomAlertDoubleBtnDialog(this);
        mGson = new Gson();
        mSharedPreferencesManager = SharedPreferencesManager.getInstance(getApplicationContext());
    }

    @Override
    public void initView() {
        List<AccountStateModel> model = mGson.fromJson(mSharedPreferencesManager.readString(BINDING_LIST, ""), new TypeToken<List<AccountStateModel>>() {
        }.getType());
        if (null != model) {
            mName = model.get(0).getUserCompanyName();
            mAccount = model.get(0).getUserAccount();
        }
        mLayoutTitleTextName.setText(getString(R.string.login_pass_authentication));
        mTvCompany.setText(mHiddenRule.nameHidden(mName));
        mTvAccount.setText(mHiddenRule.accountCommonHidden(mAccount));
        mEdPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    RetrievePassword();
                }
                return false;
            }
        });
    }

    private void isBack() {
        mDialog.setTitle(getString(R.string.whether_to_exit_the_application));
        CustomAlertDoubleBtnDialog.commitClickListener listener = new CustomAlertDoubleBtnDialog.commitClickListener() {
            @Override
            public void onClick() {
                AppUtil.getInstance().exit();
            }
        };
        mDialog.setCommitClickListener(listener);
        mDialog.showDialog();
    }

    @OnClick({R.id.btn_commit, R.id.iv_password_show, R.id.layout_title_iv_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_commit:
                RetrievePassword();
                break;
            case R.id.iv_password_show:
                if (mEdPassword.getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    mEdPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mIvPasswordShow.setImageResource(R.drawable.icon_password_open);
                } else {
                    mEdPassword.setInputType(InputType.TYPE_CLASS_TEXT |
                            InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mIvPasswordShow.setImageResource(R.drawable.icon_password_close);
                }
                mEdPassword.setSelection(mEdPassword.getText().toString().length());
                break;
            case R.id.layout_title_iv_left:
                isBack();
                break;
        }
    }

    private void RetrievePassword() {
        if (!TextUtils.isEmpty(mEdPassword.getText().toString())) {
            showProgress(R.string.loadding);
            new RetrievePasswordAPI(this).retrievePassword("wallet", mAccount, mEdPassword.getText().toString(), new RetrievePasswordAPI.Listener() {
                @Override
                public void onSuccess(VerifyPasswordModel model) {
                    if (null != model) {
                        LogUtil.log("retrievePasswordAPI---" + "onSuccess");
                        if (!TextUtils.isEmpty(model.getState())) {
                            if (TASK_SUCCESS.equals(model.getState())) {
                                LockManager.getInstance().resetLock(PasswordVerificationActivity.this);
                                PasswordVerificationActivity.this.finish();
                            } else {
                                ToastUtil.showShort(R.string.failure);
                                mEdPassword.setText("");
                            }
                        }
                    }
                    dismisProgress();
                }

                @Override
                public void onFailure(int i, String message) {
                    dismisProgress();
                    if (!TextUtils.isEmpty(message)) {
                        ToastUtil.showShort(message);
                    } else {
                        ToastUtil.showShort(R.string.check_network);
                    }
                    LogUtil.log("retrievePasswordAPI---" + "onFailure");
                }
            });
        } else {
            ToastUtil.showShort(R.string.failure);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - mFirstTime > 2000) {
                ToastUtil.showLong(R.string.again_according_to_exit_program);
                mFirstTime = System.currentTimeMillis();
            } else {
                AppUtil.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
